package ren.kane.phoenix.util.schedule;

import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author renrk(1275) on 2019-04-11 3:42 PM
 **/
@Component
@EnableScheduling
public class TaskCronChange implements SchedulingConfigurer {

    private static String cron;

    public TaskCronChange() {
        cron = "0/5 * * * * *";
        new Thread(() -> {
            try {
                Thread.sleep(15000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            cron = "0/30 * * * * *";
            System.out.println("cron change to:" + cron);
        }).start();
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        Runnable runnable = () -> System.out.println("TaskCronChange task is running ... " + new Date());
        Trigger trigger = (triggerContext) -> {
            CronTrigger cronTrigger = new CronTrigger(cron);
            return cronTrigger.nextExecutionTime(triggerContext);
        };
        scheduledTaskRegistrar.addTriggerTask(runnable, trigger);
    }
}
